<template>
  <div>
    <el-dialog append-to-body :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <el-upload
      :action="actionUrl"
      :accept="acceptType"
      :name="name"
      :disabled="disabled"
      :multiple="multiple"
      :auto-upload="autoUpload"
      :before-remove="beforeRemove"
      :list-type="listType"
      :limit="limit"
      v-if="!readonly"
      :on-error="handleError"
      :on-success="handleChange"
      :headers="headers"
      class="el-upload-editor"
      :on-preview="filePreview"
      :file-list="fileList"
      :class="{ 'limit-fill': limit == fileList.length }"
    >
      <el-button
        v-if="listType === 'text'"
        size="small"
        slot="default"
        type="primary"
        icon="el-icon-upload"
        >{{ defaultConfig.buttonText }}
      </el-button>
      <div slot="tip" class="el-upload__tip">{{ uploadTip || defaultConfig.uploadTip }}</div>
      <div
        v-if="listType === 'text'"
        class="el-upload-list__item is-success"
        slot="file"
        slot-scope="file"
      >
        <template>
          <a class="el-upload-list__item-name" @click="filePreview(file.file)"
            ><i :class="getIcoClass(file.file)"></i
            ><span style="margin-left: 8px;">{{ file.file.name }}</span>
          </a>
          <span class="download_btn" @click="download(file.file)">下载</span>
          <span @click="handleRemove(file.file)">
            <i class="el-icon-close"></i>
          </span>
        </template>
        <el-progress
          :percentage="file.file.progress"
          v-if="file.file.progress"
          class="progress"
        ></el-progress>
      </div>
    </el-upload>
    <div v-else class="sz-common-upload-readonly">
      <ul
        class="el-upload-list el-upload-list--text"
        v-if="fileList.length > 0"
      >
        <li
          v-for="(item, index) in fileList"
          :key="index"
          tabindex="0"
          class="el-upload-list__item is-success"
        >
          <template v-if="listType == 'picture-card'">
            <el-image
              style="width: 150px; height: 150px"
              :src="item.url"
              :preview-src-list="[item.url]"
              fit="cover"
            ></el-image>
          </template>
          <template v-else>
            <a class="el-upload-list__item-name" @click="previewFile(item)"
              ><i :class="getIcoClass(item)"></i
              ><span style="margin-left: 8px;">{{ item.name }}</span>
            </a>
            <span class="download_btn" @click="download(item)">下载</span>
          </template>
          <el-progress
            :percentage="item.progress"
            v-if="item.progress"
            class="progress"
          ></el-progress>
        </li>
      </ul>

      <div v-else style="height: 40px;"></div>
    </div>
  </div>
</template>

<script>
import _ from "lodash";
import axios from "axios";
import qs from "query-string";

export default {
  name: "sz-upload",
  props: {
    // action: {
    //   type: String,
    //   default:
    //     'http://47.97.101.122:23888/api/sys/file/db/upload?path=workflow"'
    // },
    accept: {
      type: String,
      default: ""
    },
    uploadTip: {
      type: String,
      default: ""
    },
    config: {
      type: Object,
      default: function() {
        return {};
      }
    },
    // 只读属性
    readonly: {
      type: Boolean,
      default: false
    },
    // 默认值
    value: {
      type: Array | String,
      default: function() {
        return [];
      }
    },
    name: {
      type: String,
      default: "file"
    },
    limit: {
      type: Number,
      default: 100
    },
    disabled: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    // 业务编码 null 使用页面属性的配置，否则根据key查询相应的配置
    businessKey: {
      type: String,
      default: "WORKFLOW"
    },
    "auto-upload": {
      type: Boolean,
      default: true
    },
    /**
     * 描述：显示水印
     * 时间： 2020/10/29
     */
    waterMark: {
      type: Boolean,
      default: false
    },
    /**
     * 描述：水印内容
     * 时间： 2020/10/29
     */
    waterText: {
      type: String,
      default: ""
    },
    /**
     * 描述：是否加标签
     * 时间： 2020/11/7
     */
    isLabel: {
      type: Boolean,
      default: false
    },
    /**
     * 描述：标签内容
     * 时间： 2020/11/7
     */
    labelText: {
      type: String,
      default: ""
    },
    /**
     * 描述：x坐标
     * 时间： 2020/11/7
     */
    labelX: {
      type: Number | String,
      default: 0
    },
    /**
     * 描述：y坐标
     * 时间： 2020/11/7
     */
    labelY: {
      type: Number | String,
      default: 0
    },
    "list-type": {
      type: String,
      default: "text"
    }
  },
  data() {
    return {
      actionUrl: window.api.sysUploadUrl + "?path=workflow",
      dialogVisible: false,
      dialogImageUrl: "",
      headers: {
        token: window.sessionStorage.getItem("token"),
        userRole: "ADMIN"
      },
      defaultConfig: {
        buttonText: "上传",
        uploadTip: "只能上传jpg/png文件，且不超过500kb"
      },
      fileList: [],
      acceptType: _.clone(this.accept),
      uploadList: [],
      imageHead: window.api.image + "/"
    };
  },
  watch: {},
  mounted() {
    if (this.value) {
      this.value.map(item => {
        let imgUrl = item.value;
        if (item.value && item.value.indexOf("http") == -1) {
          imgUrl = this.imageHead + item.value;
        }
        this.fileList.push({
          name: item.fileName || "文件",
          url: item.id || imgUrl
        });
        this.uploadList.push({
          name: item.fileName,
          url: item.id || imgUrl
        });
      });
    }
    Object.assign(this.defaultConfig, this.config);
    if (this.businessKey) {
      this.getSettingByKey();
    }
  },
  methods: {
    getIcoClass(item) {
      if (!item.name) {
        return "fa fa-file-word-o doc_blue";
      }
      let type = item.name.split(".")[1];
      switch (type) {
        case "doc":
        case "docx":
          return "fa fa-file-word-o doc_blue";
          break;
        case "pdf":
          return "fa fa-file-pdf-o pdf_red";
          break;
        case "png":
        case "jpg":
          return "fa fa-file-image-o image_green";
          break;
        default:
          return "fa fa-file-text-o image_green";
          break;
      }
    },
    //错误
    handleError(err, file, fileList) {
      this.$notify.error({
        title: "错误",
        dangerouslyUseHTMLString: true,
        duration: 2000,
        message: `<p style="display: block;width: 260px; word-wrap: break-word">${
          JSON.parse(err.message).message
        }</p>`
      });
    },
    /**
     * 描述：根据业务获取模块的上传类型和提示
     * 时间： 2021/3/22
     */
    getSettingByKey() {
      this.API.getModuleSettingByKey({ key: this.businessKey }).then(res => {
        this.acceptType = "";
        if (res.data.fileTypes) {
          this.actionUrl =
            window.api.sysUploadUrl +
            `?path=workflow&fileTypes=${res.data.fileTypes}`;
          let arr = res.data.fileTypes.split(",");
          let nextArr = arr.map(item => {
            return "." + item;
          });
          this.acceptType = nextArr.join(",");
        }
        if (this.listType == "picture-card") {
          this.actionUrl = window.api.uploadUrl1 + "?path=workflow";
        }
        if (this.listType == "picture-card") {
          return;
        }
        this.defaultConfig.uploadTip = res.data.description
          ? res.data.description
          : "";
      });
    },
    // 删除文件前回调
    beforeRemove(file, fileList) {
      // this.fileList = fileList;
      this.handleRemove(file);
    },
    // 移除文件
    handleRemove(file) {
      // console.log(file, this.fileList, this.uploadList);
      let index = this.fileList.findIndex((item, index, arr) => {
        if (item.response) {
          return item.response.id == file.response.id;
        } else if (item.url) {
          return item.url == file.url;
        }
      });
      this.uploadList.splice(index, 1);
      this.fileList = this.uploadList;
      let tem = [];
      if (this.fileList) {
        this.fileList.map(item => {
          if (item.response) {
            tem.push(item.response);
          } else if (item.url) {
            tem.push({
              fileName: item.name,
              id: item.url
            });
          }
        });
      }
      this.$emit("input", tem);
    },
    previewFile(item) {
      this.openTabPage(
        window.api.preFile +
          "?url=" +
          window.api.secretFilePreview +
          item.url +
          "?token=" +
          window.sessionStorage.getItem("token")
      );
    },
    // 下载
    download(item) {
      // console.log(item);
      // 已开始下载，不允许再次点击
      if (item.progress) {
        return;
      }
      let fileDownload = require("js-file-download");
      let taskId = this.$route.query.taskId;
      // console.log(taskId, "taskId");
      this.API.getLabelTextByTaskId({
        taskId: taskId,
        labelText: this.labelText
      }).then(res => {
        let para = {
          id: item.url,
          waterMark: this.waterMark,
          waterText: this.waterText,
          isLabel: this.isLabel,
          labelText: res.data,
          labelX: this.labelX,
          labelY: this.labelY,
          taskId: taskId
        };
        this.ExportApi.getSpecialFile(para, evt => {
          let percentage = Math.floor((evt.loaded / evt.total) * 100);
          if (item.progress) {
            item.progress = percentage;
          } else {
            this.$set(item, "progress", percentage);
          }
          if (percentage === 100) {
            delete item.progress;
          }
        })
          .then(res => {
            const disposition = res.headers["content-disposition"];
            let fileName = this.getFileName(disposition);
            fileDownload(res.data, fileName);
          })
          .finally(() => {});
      });
    },
    handleChange(response, file, fileList) {
      if (response.value) {
        const imgUrl = this.imageHead + response.value;
        this.fileList.push({
          name: "文件",
          url: imgUrl
        });
      } else {
        this.fileList = fileList;
      }
      let tem = [];
      this.uploadList = [];
      if (fileList) {
        fileList.map(item => {
          if (item.response) {
            tem.push(item.response);
            this.uploadList.push(item);
          } else if (item.url) {
            tem.push({
              fileName: item.name,
              id: item.url
            });
            this.uploadList.push(item);
          }
        });
      }
      // console.log(response, file, fileList);
      this.$emit("input", tem);
    },
    // 文件预览 text,pdf,txt,其他格式下载
    filePreview(file) {
      if (file.url && this.$props.listType == "picture-card") {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
        return;
      }
      if (file.url) {
        this.openTabPage(
          window.api.preFile +
            "?url=" +
            window.api.secretFilePreview +
            file.url +
            "?token=" +
            window.sessionStorage.getItem("token")
        );
      } else {
        if (file.response) {
          this.openTabPage(
            window.api.preFile +
              "?url=" +
              window.api.secretFilePreview +
              file.response.id +
              "?token=" +
              window.sessionStorage.getItem("token")
          );
        }
      }
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .el-upload-list__item {
  margin-bottom: 10px !important;
}

.progress {
  top: 25px;
}
.limit-fill {
  /deep/ .el-upload--picture-card {
    display: none;
  }
}
.el-upload-editor {
  .el-upload-list__item {
    margin-top: 0;
    background-color: #ffffff;
    border-radius: 10px;
    display: flex;
  }

  .el-upload-list__item-name {
    margin-right: 0px;
    font-size: 14px;
    font-family: Source Han Sans CN;
    font-weight: 400;
    line-height: 29px;
    color: #303030;
    opacity: 1;
  }

  .download_btn {
    color: #0075ff;
    padding-left: 20px;
    line-height: 29px;
    cursor: pointer;
    margin-right: 20px;
    width: 60px;
  }
}

.sz-common-upload-readonly {
  margin-top: 20px;

  .download_btn {
    color: #0075ff;
    padding-left: 20px;
    line-height: 29px;
    cursor: pointer;
    width: 60px;
  }

  .el-upload-list__item {
    margin-top: 0px;
    background-color: #ffffff;
    border-radius: 10px;
    display: flex;
  }

  .el-upload-list__item-name {
    margin-right: 0px;
    font-size: 14px;
    font-family: Source Han Sans CN;
    font-weight: 400;
    line-height: 29px;
    color: #303030;
    opacity: 1;
  }
}
</style>
